<template>
  <div class="app-container">
    <el-card class="product-container" shadow="never">
      <!-- 步骤条 -->
      <el-steps align-center :active="activeStep" finish-status="success">
        <el-step title="商品信息"/>
        <el-step title="商品营销"/>
        <el-step title="商品图片"/>
        <el-step title="商品详情"/>
      </el-steps>

      <!-- 商品表单 -->
      <el-form ref="form" :model="form" label-width="100px" size="mini" :rules="rules">

        <!-- 商品详情 -->
        <div v-show="activeStep===0" class="product-info">
          <el-row :gutter="20">
            <el-col :span="12" :offset="0">
              <el-form-item label="商品分类" prop="productCategoryId">
                <el-cascader v-model="activeProductCategory" clearable filterable placeholder="选择分类" style="width: 100%"
                             :options="productCategoryTreeList"
                             :props="{ expandTrigger: 'hover', value: 'id', label: 'name' }"
                             @change="changeProductCategory"/>
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item label="商品品牌" prop="brandId">
                <el-select v-model="form.brandId" style="width: 100%" placeholder="选择品牌" clearable filterable>
                  <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24" :offset="0">
              <el-form-item label="商品名称" prop="name">
                <el-input v-model="form.name" placeholder="商品名称" clearable/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24" :offset="0">
              <el-form-item label="副标题" prop="subTitle">
                <el-input v-model="form.subTitle" placeholder="副标题" clearable/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24" :offset="0">
              <el-form-item label="排序" prop="sort">
                <el-input-number v-model="form.sort" style="width: 100%" controls-position="right" :min="1"
                                 placeholder="排序" clearable/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24" :offset="0">
              <el-form-item label="商品描述" prop="pdesc">
                <el-input v-model="form.pdesc" type="textarea" :rows="4" placeholder="商品描述" clearable
                          :autosize="{ minRows: 4, maxRows: 10 }"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item>
                <el-button @click="cancel">返回</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item>
                <el-button type="primary" @click="activeStep++">下一步，填写商品营销</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 商品营销 -->
        <div v-show="activeStep === 1" class="product-info">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="上架" prop="publishStatus">
                <el-switch v-model="form.publishStatus" :active-value="1" :inactive-value="0"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="新品" prop="newStatus">
                <el-switch v-model="form.newStatus" :active-value="1" :inactive-value="0"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="推荐" prop="recommendStatus">
                <el-switch v-model="form.recommendStatus" :active-value="1" :inactive-value="0"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="禁用状态" prop="status">
                <el-switch v-model="form.status" :active-value="1" :inactive-value="0"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="可获取积分" prop="point">
                <el-input-number v-model="form.point" style="width: 100%" controls-position="right"
                                 placeholder="购买可获取积分" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="价格">
                <el-input-number v-model="form.price" style="width: 100%" controls-position="right"
                                 placeholder="价格" clearable/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item>
                <el-button @click="activeStep--">上一步，填写商品信息</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item>
                <el-button type="primary" @click="activeStep++">下一步，填写商品图片</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 商品图片开始 -->
        <div v-show="activeStep === 2" class="product-info">
          <el-row :gutter="20">
            <el-col :span="24" :offset="0">
              <el-form-item label="商品图片" prop="pic">
                <el-upload class="up-img-uploader" :action="imageAction" :show-file-list="false"
                           :on-success="handleUploadSuccess" :headers="headers">
                  <img v-if="imageUrl" :src="imageUrl" class="up-img" alt="">
                  <i v-else class="el-icon-plus avatar-uploader-icon"/>
                </el-upload>
                <div style="color: red">
                  请上传封面图片，该图片用于 列表页展示
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24" :offset="0">
              <el-form-item label="轮播图" prop="albumPics">
                <el-upload class="up-img-uploader" :action="imageAction" list-type="picture-card"
                           :on-success="handleBannerUploadSuccess" :headers="headers" :on-remove="handleRemove">
                  <i class="el-icon-plus avatar-uploader-icon"/>
                </el-upload>
                <div style="color: red;margin-top: 30px">
                  请上传商品详情轮播图，如果不上传，默认采用上面的图片展示
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item>
                <el-button @click="activeStep--">上一步，填写商品营销</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item>
                <el-button type="primary" @click="activeStep++">下一步，填写商品详情</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 商品详情 -->
        <div v-show="activeStep === 3" class="product-info">
          <el-row :gutter="20">
            <el-col :span="24" :offset="0">
              <el-form-item label="商品详情" prop="content">
                <tinymce v-model="form.content" :height="400"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item>
                <el-button @click="activeStep--">上一步，填写商品图片</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item>
                <el-button type="primary" @click="submitForm">提交</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </el-card>

  </div>
</template>

<script>
import Tinymce from '@c/Tinymce'
import { getProductCategoryOptionSelect } from '@a/beauty/productCategory'
import { getToken } from '@u/auth'
import { getBrandsByProductCategoryId } from '@a/beauty/brand'
import { addProduct } from '@a/beauty/product'

export default {
  name: 'add',
  components: {
    Tinymce
  },
  data() {
    return {
      // 存放临时的轮播图
      albumPicList: [],
      // 品牌数组
      brandList: [],
      // 当前选中的分类
      activeProductCategory: {},
      // 商品分类树
      productCategoryTreeList: [],
      imageUrl: null, // 上传图片回显
      headers: {
        // 上传文件的请求头
        Authorization: 'Bearer ' + getToken()
      },
      // 请求地址
      imageAction: process.env.VUE_APP_BASE_API + process.env.VUE_APP_FILE_UPLOAD, // 上传的图片服务器地址
      // 当前选中的步骤条
      activeStep: 0,
      form: {},
      // 表单校验
      rules: {
        brandId: [
          { required: true, message: '商品品牌不能为空', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '商品状态不能为空', trigger: 'blur' }
        ],
        publishStatus: [
          { required: true, message: '上架状态不能为空', trigger: 'blur' }
        ],
        newStatus: [
          { required: true, message: '新品状态不能为空', trigger: 'blur' }
        ],
        recommendStatus: [
          { required: true, message: '推荐状态不能为空', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '排序不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '商品名称不能为空', trigger: 'blur' }
        ],
        productCategoryId: [
          { required: true, message: '商品分类不能为空', trigger: 'blur' }
        ],
        pic: [
          { required: true, message: '商品图片不能为空', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '商品价格不能为空', trigger: 'blur' }
        ],
        point: [
          { required: true, message: '购买积分不能为空', trigger: 'blur' }
        ],
        subTitle: [
          { required: true, message: '副标题不能为空', trigger: 'blur' }
        ],
        pdesc: [
          { required: true, message: '商品描述不能为空', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '商品详情不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getProductCategoryOptionSelect()
  },
  methods: {
    // 选中的分类发生变化时触发
    changeProductCategory(item) {
      if (!item || !item[0]) {
        this.brandList = []
        // 让form中的brandId为null
        this.$set(this.form, 'brandId', null)
        this.$set(this.form, 'productCategoryId', null)
        return
      }
      // 取出最后一个分类ID
      const leafCategory = item[item.length - 1]
      // 赋值给商品分类ID
      this.$set(this.form, 'productCategoryId', leafCategory)
      // 根据商品分类id加载所有品牌
      this.getBrandsByCategoryId()
    },
    // 根据商品分类id查询所有品牌
    getBrandsByCategoryId() {
      getBrandsByProductCategoryId(this.form.productCategoryId).then(res => {
        this.brandList = res.data
      })
    },
    // 获取商品分类列表
    getProductCategoryOptionSelect() {
      getProductCategoryOptionSelect().then(response => {
        //  我们只要二级的 因为在存品牌分类的时候我们只是存二级分类id 和品牌进行关联
        let data = response.data.filter(e=>e.level!==3)
        // console.log(this.handleTree(response.data))
        this.productCategoryTreeList = this.handleTree(data)
      })
    },
    /** 上传封面成功 **/
    handleUploadSuccess(res, file) {
      // console.log(res)
      if (res.code == 200) {
        const { url } = res.data
        this.msgNoticeSuccess('上传成功')
        this.imageUrl = url
        this.form.pic = url
      }
    },
    // 处理轮播图上传成功
    handleBannerUploadSuccess(res, file) {
      if (res.code == 200) {
        this.albumPicList.push({
          uid: file.uid,
          url: res.data.url
        })
      }
    },
    // 删除轮播图触发
    handleRemove(file, fileList) {
      // 根据uid去删除
      this.albumPicList.splice(
        this.albumPicList.findIndex(e => e.uid === file.uid)
      )
    },
    // 提交表单
    submitForm() {
      let albumPicStr = ''
      this.albumPicList.forEach(e => {
        albumPicStr += e.url + ','
      })
      albumPicStr = albumPicStr.substring(0, albumPicStr.lastIndexOf(','))
      // console.log('轮播图:', albumPicStr.split(','))
      this.form.albumPics = albumPicStr
      // console.log('form:', this.form)
      this.$refs['form'].validate(valid => {
        if (valid) {
          addProduct(this.form).then(res => {
            this.msgNoticeSuccess('新增成功')
            this.$router.push({ path: '/project/product' })
          })
        }
      })

    },
    cancel() {
      this.$router.push('/project/product')
    }
  }
}
</script>

<style scoped lang="scss">
.product-container {
  width: 1000px;
  margin: auto;
  padding: 40px;

  .product-info {
    padding-top: 30px;
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.up-img-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #000000;
  background-color: #e8e8e8;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
}

.up-img {
  width: 148px;
  height: 148px;
  display: block;
}
</style>
